var userNameField = $('#login-username-field');
var passwordField = $('#login-password-field');
var signInButton = $('#login-signin-button');

var signInButtonClick = function() {
	if (signInButton.hasClass('disabled')) return;
	signInButton.addClass('disabled');
	signInButton.button('loading');

	var username = userNameField.val();
	var password = passwordField.val();

	$.post(app.baseUrl() + 'index.php/home/logon',
	   {
	   		'username' : username,
	   		'password' : password
	   }).done(function(response) {
	   		var user = null;

	   		try {
	   			user = JSON.parse(response);
	   		}
	   		catch (ex) {

	   		}

	   		if (user != null) {
	   			if (user['UserId'] != undefined &&
		   			user['UserId'] != null) {
		   			if (user['IsLoggedIn']) window.location.replace(app.baseUrl());
		   			else {
		   				warningGritter({
							title: 'User Login',
							text: 'Invalid username and / or password.'
						});
		   			}
		   		}
		   		else {
		   			warningGritter({
						title: 'User Login',
						text: 'Invalid username and / or password.'
					});
		   		}
	   		}
	   }).fail(function(response) {
	   		try {
	   			console.error(response);
	   		}
	   		catch(ex) {
	   		}

	   		errorGritter({
				title: 'Oooops',
				text: 'Something went wrong while trying to log you in.'
			});
	   }).always(function(response) {
	   		signInButton.removeClass('disabled');
			signInButton.button('reset');
	   });
};

var logonFieldKeyPress = function(e) {
	if (e.keyCode == 13) signInButton.trigger('click');
};

$(document).ready(function() {
	signInButton.unbind('click');
	signInButton.click(signInButtonClick);

	userNameField.unbind('keypress');
	userNameField.keypress(logonFieldKeyPress);

	passwordField.unbind('keypress');
	passwordField.keypress(logonFieldKeyPress);
});